package com.sdy.dataexchange.meta.util;

import com.sdy.dataexchange.meta.model.MetadataErrorRecord;
import com.sdy.dataexchange.meta.model.MetadataModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author: 王越洋
 * @version: v1.0
 * @description: com.sdy.dataexchange.meta.util
 * @date:2019/11/8
 */

@Slf4j
@Component
public class TableUtil {
    /**
     * 生成带Key 的 map
     *
     * @param list
     * @return
     */
    private Map<String, MetadataModel> createMap(List<MetadataModel> list) {
        Map<String, MetadataModel> map = new HashMap<>();
        for (MetadataModel m : list) {
            String key = "";
            String tableName = m.getModelName();
            if (tableName != null && !"".equals(tableName)) {
                key += tableName;
            }
            map.put(key, m);
        }
        return map;
    }

    /**
     * 对比新数据 与 旧数据 之间的不同
     *
     * @param target
     * @param comMap
     * @return
     */
    private List<MetadataErrorRecord> getDifferentList(Map<String, MetadataModel> target, Map<String, MetadataModel> comMap) {
        List<MetadataErrorRecord> merList = new ArrayList<>();
        for (Map.Entry<String, MetadataModel> entry : target.entrySet()) {
            String key = entry.getKey();
            if (!comMap.containsKey(key)) {
                MetadataErrorRecord m = new MetadataErrorRecord();
                log.info("数据源删除了表"+target.get(key).getModelName());
                m.setDbId(target.get(key).getDbId());
                m.setTableName(target.get(key).getModelName());
                m.setModId(target.get(key).getId());
                m.setErrorType(1);
                m.setErrorDescribe("数据源:"+target.get(key).getModelIdentifying()+"  删除了:"+target.get(key).getModelName()+"表");
                merList.add(m);
            }
        }
        for (Map.Entry<String, MetadataModel> entry : comMap.entrySet()) {
            String key = entry.getKey();
            if (!target.containsKey(key)) {
                MetadataErrorRecord m = new MetadataErrorRecord();
                log.info("数据源新增了表"+comMap.get(key).getModelName());
                m.setDbId(comMap.get(key).getDbId());
                m.setTableName(comMap.get(key).getModelName());
                m.setErrorType(2);
                m.setErrorDescribe("数据源:"+comMap.get(key).getModelIdentifying()+"  新增了:"+comMap.get(key).getModelName()+"表");
                merList.add(m);
            }
        }
        return merList;
    }

    public List<MetadataErrorRecord> getComResulMap(List<MetadataModel> formerData, List<MetadataModel> newData) {
        Map<String, MetadataModel> formerDataMap = createMap(formerData);
        Map<String, MetadataModel> newDataMap = createMap(newData);
        List<MetadataErrorRecord> reduce = getDifferentList(formerDataMap, newDataMap);
        return reduce;
    }
}
